import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, message, Modal, Dropdown, Typography, Badge } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, CalendarOutlined, ExportOutlined } from '@ant-design/icons';
import { getDailySentenceList, deleteDailySentence, createDailySentence, updateDailySentence, autoScheduleDailySentences } from '@/services/learningContentApi';
import DailySentenceForm from './components/DailySentenceForm';
import SentenceCalendar from './components/SentenceCalendar';
import dayjs from 'dayjs';

const { Text } = Typography;

const DailySentenceList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [sentenceFormVisible, setSentenceFormVisible] = useState(false);
  const [calendarVisible, setCalendarVisible] = useState(false);
  const [currentSentence, setCurrentSentence] = useState<LEARNING.DailySentenceModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');



  // 表格列定义
  const columns: ProColumns<LEARNING.DailySentenceModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '句子内容',
      dataIndex: 'chinese',
      width: 300,
      ellipsis: true,
      copyable: true,
      render: (text) => (
        <Text style={{ maxWidth: 280 }} ellipsis={{ tooltip: text }}>
          {text}
        </Text>
      ),
    },
    {
      title: '拼音',
      dataIndex: 'pinyin',
      width: 200,
      search: false,
      ellipsis: true,
      render: (pinyin) => (
        pinyin ? (
          <Text type="secondary" style={{ fontSize: '12px' }}>
            {pinyin}
          </Text>
        ) : '-'
      ),
    },
    {
      title: '翻译',
      dataIndex: 'english',
      width: 200,
      search: false,
      ellipsis: true,
      render: (translation) => (
        translation ? (
          <Text type="secondary">
            {translation}
          </Text>
        ) : '-'
      ),
    },
    {
      title: '来源',
      dataIndex: 'source',
      width: 120,
      search: false,
      ellipsis: true,
      render: (source) => source || '-',
    },
    {
      title: '音频',
      dataIndex: 'audio_url',
      width: 120,
      search: false,
      render: (_, record) => (
        record.audio_url ? (
          <a
            href={record.audio_url}
            target="_blank"
            rel="noopener noreferrer"
            style={{ color: '#1890ff' }}
          >
            🔊 播放
          </a>
        ) : '-'
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      width: 120,
      valueType: 'select',
      valueEnum: {
        inspirational: { text: '励志名言' },
        poetry: { text: '诗词歌赋' },
        proverb: { text: '谚语俗语' },
        philosophy: { text: '哲理感悟' },
        daily: { text: '日常用语' },
        festival: { text: '节日祝福' },
      },
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      width: 100,
      valueType: 'select',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Default' },
      },
      render: (_, record) => {
        return (
          <Tag color={record.is_active ? 'green' : 'default'}>
            {record.is_active ? '启用' : '禁用'}
          </Tag>
        );
      },
    },
    {
      title: '排期日期',
      dataIndex: 'scheduled_date',
      width: 120,
      search: false,
      valueType: 'date',
      render: (_, record) => record.date ? dayjs(record.date).format('MM-DD') : '-',
    },
    {
      title: '浏览次数',
      dataIndex: 'view_count',
      width: 100,
      search: false,
      render: (count) => (
        <Badge count={count || 0} showZero color="#52c41a" />
      ),
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      width: 80,
      search: false,
      render: (count) => (
        <Badge count={count || 0} showZero color="#ff4d4f" />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          size="small"
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'schedule',
                label: '排期',
                icon: <CalendarOutlined />,
                onClick: () => handleSchedule(record),
              },
              {
                key: 'status',
                label: record.is_active ? '禁用' : '启用',
                onClick: () => handleStatusChange(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理编辑
  const handleEdit = (record: LEARNING.DailySentenceModel) => {
    setCurrentSentence(record);
    setEditMode('edit');
    setSentenceFormVisible(true);
  };

  // 处理排期
  const handleSchedule = (record: LEARNING.DailySentenceModel) => {
    Modal.confirm({
      title: '排期设置',
      content: '请选择要排期的日期',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 这里应该打开日期选择器
        message.info('请在日历视图中进行排期操作');
        setCalendarVisible(true);
      },
    });
  };

  // 处理状态变更
  const handleStatusChange = (record: LEARNING.DailySentenceModel) => {
    const newStatus = !record.is_active;
    const actionText = newStatus ? '启用' : '禁用';

    // 安全地获取句子内容的前20个字符
    const sentencePreview = record.chinese
      ? record.chinese.substring(0, 20)
      : '此句子';

    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}句子 "${sentencePreview}..." 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await updateDailySentence(record.id, { is_active: newStatus });
          message.success(`句子${actionText}成功`);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`句子${actionText}失败`);
        }
      },
    });
  };

  // 处理删除
  const handleDelete = (record: LEARNING.DailySentenceModel) => {
    // 安全地获取句子内容的前20个字符
    const sentencePreview = record.chinese
      ? record.chinese.substring(0, 20)
      : '此句子';

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除句子 "${sentencePreview}..." 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteDailySentence(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentSentence(undefined);
    setEditMode('create');
    setSentenceFormVisible(true);
  };

  // 处理批量排期
  const handleBatchSchedule = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要排期的句子');
      return;
    }

    Modal.confirm({
      title: '批量排期',
      content: `确定要为选中的 ${selectedRowKeys.length} 个句子进行自动排期吗？系统将从明天开始按顺序排期。`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await autoScheduleDailySentences({
            start_date: dayjs().add(1, 'day').format('YYYY-MM-DD'),
            end_date: dayjs().add(selectedRowKeys.length, 'day').format('YYYY-MM-DD'),
          });
          message.success('批量排期成功');
          setSelectedRowKeys([]);
          actionRef.current?.reload();
        } catch (error) {
          message.error('批量排期失败');
        }
      },
    });
  };

  return (
    <PageContainer>
      <ProTable<LEARNING.DailySentenceModel>
        headerTitle="每日一句列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建句子
          </Button>,
          <Button
            key="calendar"
            icon={<CalendarOutlined />}
            onClick={() => setCalendarVisible(true)}
          >
            日历视图
          </Button>,
        ]}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => (
          <Space size={16}>
            <a onClick={handleBatchSchedule}>批量排期</a>
          </Space>
        )}
        request={async (params) => {
          const response = await getDailySentenceList({
            page: params.current,
            limit: params.pageSize,
            keyword: params.chinese,
            source: params.source,
            is_active: params.is_active,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1400 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 句子表单弹窗 */}
      <DailySentenceForm
        visible={sentenceFormVisible}
        initialValues={currentSentence}
        onCancel={() => setSentenceFormVisible(false)}
        onSubmit={async (values) => {
          try {
            if (editMode === 'edit' && currentSentence) {
              await updateDailySentence(currentSentence.id, values);
              message.success('句子更新成功');
            } else {
              await createDailySentence(values);
              message.success('句子创建成功');
            }
            setSentenceFormVisible(false);
            actionRef.current?.reload();
          } catch (error) {
            message.error(editMode === 'edit' ? '句子更新失败' : '句子创建失败');
          }
        }}
      />

      {/* 日历视图弹窗 */}
      <SentenceCalendar
        visible={calendarVisible}
        onCancel={() => setCalendarVisible(false)}
        onSuccess={() => {
          setCalendarVisible(false);
          actionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default DailySentenceList;
